package com.github.codemperor.core.token.aop;

import com.github.codemperor.core.HandlerOrder;
import com.github.codemperor.core.token.CurrentUserInfo;
import com.github.codemperor.core.token.context.CurrentUserContext;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;

/**
 * 用于获取网关透传的用户信息，后期考虑可以多加token2次认证等
 *
 * @author codemperor
 */
@Order(HandlerOrder.USER_INFO_AOP)
@Aspect
public class UserInfoAop {
    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Around("@within(restController) || @annotation(restController)")
    public Object secured(ProceedingJoinPoint point, RestController restController) throws Throwable {
        try {
            RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);

            CurrentUserInfo user = new CurrentUserInfo(request);
            CurrentUserContext.set(user);

            log.debug("[UserInfoAop] before user: {}", CurrentUserContext.get());

            //before
            Object result = point.proceed();
            //after

            CurrentUserContext.remove();

            log.debug("[UserInfoAop] after user: {}", CurrentUserContext.get());

            return result;
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            CurrentUserContext.remove();
        }
    }
}
